package cn.com.pajx.pajx_visitor_v3.ui.activity;

import android.annotation.SuppressLint;
import android.text.TextUtils;

import com.telpo.scan.ScanCallBack;
import com.telpo.scan.ScanTool;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import cn.com.pajx.pajx_visitor_v3.R;
import cn.com.pajx.pajx_visitor_v3.base.BaseActivity;
import cn.com.pajx.pajx_visitor_v3.bean.EventMessage;
import cn.com.pajx.pajx_visitor_v3.ui.fragment.VisitorInfoFragment;
import cn.com.pajx.pajx_visitor_v3.utils.AppConstant;
import cn.com.pajx.pajx_visitor_v3.utils.LogUtils;

/**
 * 扫码出校页面
 */
@SuppressLint("NonConstantResourceId")
public class ScanCodeActivity extends BaseActivity implements ScanCallBack {

    private VisitorInfoFragment visitorInfoFragment;

    @Override
    protected void beforeSetContentView() {

    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_scan_code;
    }

    @Override
    protected void initView() {
        setHeadTitle("扫码出校");
        EventBus.getDefault().register(this);
        initDownTimer();
        initScanTool();
    }

    /**
     * 初始化扫码工具
     */
    private void initScanTool() {
        try {
            ScanTool.GET.initSerial(this, "/dev/ttyS7", 115200);
            ScanTool.GET.setScanCallBack(this);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public void onScanCallBack(String data) {
        LogUtils.e("scanData=" + data);
        cancelDownTimer();
        String vis_id = loadVisiteId(data);
        if (visitorInfoFragment == null && getSupportFragmentManager() != null && !TextUtils.isEmpty(vis_id)) {
            visitorInfoFragment = VisitorInfoFragment.newInstance(vis_id, AppConstant.VISITE_END);
            visitorInfoFragment.show(getSupportFragmentManager(), "visitorInfoFragment");
            visitorInfoFragment = null;
        }
    }

    @Override
    public void onInitScan(boolean isSuccess) {
        ScanCallBack.super.onInitScan(isSuccess);
        LogUtils.e("isSuccess=" + isSuccess);
        ScanTool.GET.playSound(true);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventBusMessage(EventMessage bean) {
        if (TextUtils.equals(AppConstant.FRAGMENTDIALOG_DISMISS, bean.getMessage())) {
            resetDownTimer();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        releaseScanTool();
    }

    /**
     * 释放扫码工具
     */
    private void releaseScanTool() {
        try {
            ScanTool.GET.release();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}